package com.example.service.impl;

import com.example.domain.PageResult;
import com.example.domain.ResponseResult;
import com.example.domain.vo.UserVo;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.util.BeanCopyUtil;
import com.example.util.PageUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hlc
 * @version 1.0
 * @date 2022/10/22 9:39
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public ResponseResult<PageResult<UserVo>> getUserPage(Integer pageNumber, Integer pageSize) {
        PageResult<UserVo> result = PageUtil.getPageResult(getPageInfo(pageNumber, pageSize));
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult<?> deleteUser(Long userId) {
        userMapper.deleteById(userId);
        return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult<?> deleteUsers(Long[] ids) {
        userMapper.deleteByIdList(ids);
        return ResponseResult.okResult("删除成功");
    }

    private PageInfo<UserVo> getPageInfo(Integer pageNumber, Integer pageSize) {
        List<UserVo> userList;
        try (
                Page<Object> ignored = PageHelper.startPage(pageNumber, pageSize)
        ) {
            userList = BeanCopyUtil.copyBeanList(userMapper.selectAll(), UserVo.class);
        }
        return new PageInfo<>(userList);
    }
}
